<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

// 数据存储
const publishedList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const keywords = ref('');
const dateRange = ref([]);
const modifyDialogVisible = ref(false);
const modifyTime = ref('');
const currentItem = ref(null);

// 接口请求 - 优先本地发布数据，后接接口数据，合并本地修改
const fetchPublishedNews = async () => {
    try {
        // 1. 读取本地发布的新闻
        let localPublishedData = localStorage.getItem('publishedNews')
        localPublishedData = localPublishedData ? JSON.parse(localPublishedData) : []

        // 2. 读取本地修改的时间记录
        const localModifiedData = localStorage.getItem('modifiedNews');
        const modifiedMap = localModifiedData ? JSON.parse(localModifiedData) : {};

        // 3. 请求接口获取已发布新闻
        const params = {
            current: currentPage.value,
            currentSize: pageSize.value,
            keywords: keywords.value,
            isPublished: 1,
            ...(dateRange.value.length ? {
                startTime: dateRange.value[0],
                endTime: dateRange.value[1]
            } : {})
        };
        const res = await request.get('/news/newsList', { params });
        const apiData = res.code === 200 ? res.data.records || [] : [];

        // 4. 合并接口数据与本地修改时间
        const processedApiData = apiData.map(item => {
            return modifiedMap[item.id] ? { ...item, ...modifiedMap[item.id] } : item;
        });

        // 5. 合并本地发布数据+ 处理后的接口数据，去重
        const localIds = localPublishedData.map(item => item.id);
        const finalData = [
            ...localPublishedData, // 本地发布数据在最顶部
            ...processedApiData.filter(item => !localIds.includes(item.id)) 
        ];

        // 6. 更新页面数据
        publishedList.value = finalData;
        total.value = finalData.length; 
    } catch (error) {
        console.error('获取已发布新闻失败:', error);
        // 异常时仅显示本地数据
        let localPublishedData = localStorage.getItem('publishedNews')
        localPublishedData = localPublishedData ? JSON.parse(localPublishedData) : []
        publishedList.value = localPublishedData;
        total.value = localPublishedData.length;
    }
};

// 打开修改时间弹窗
const openModifyDialog = (item) => {
    currentItem.value = { ...item };
    // 优先显示本地修改过的时间，其次是新闻本身的时间
    modifyTime.value = item.modifiedNewsTime || item.newsTime;
    modifyDialogVisible.value = true;
};

// 确认修改时间
const confirmModify = () => {
    if (!currentItem.value || !modifyTime.value) return;

    // 1. 更新本地修改记录
    const localData = localStorage.getItem('modifiedNews');
    const modifiedMap = localData ? JSON.parse(localData) : {};

    modifiedMap[currentItem.value.id] = {
        ...modifiedMap[currentItem.value.id],
        modifiedNewsTime: modifyTime.value
    };
    localStorage.setItem('modifiedNews', JSON.stringify(modifiedMap));

    // 2. 实时更新页面显示
    const index = publishedList.value.findIndex(item => item.id === currentItem.value.id);
    if (index !== -1) {
        publishedList.value[index] = {
            ...publishedList.value[index],
            modifiedNewsTime: modifyTime.value
        };
    }

    ElMessage.success('时间修改成功（本地存储）');
    modifyDialogVisible.value = false;
};

// 搜索与重置（支持搜索本地+接口数据）
const handleSearch = () => {
    currentPage.value = 1;
    fetchPublishedNews();
};

const handleReset = () => {
    keywords.value = '';
    dateRange.value = [];
    currentPage.value = 1;
    fetchPublishedNews();
};

// 分页变更
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    fetchPublishedNews();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchPublishedNews();
};

// 页面初始化时加载数据
onMounted(() => {
    fetchPublishedNews();
});
</script>

<template>
    <div class="published-news">
        <!-- 顶部信息栏 -->
        <div class="top-nav">
            <h1 class="page-title">news.pued</h1>
        </div>
        <div class="top-bar">
            <h3 class="publish-count">共发布 {{ total }} 期</h3>
            <div class="filter-area">
                <el-date-picker v-model="dateRange" type="daterange" range-separator="→" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" style="margin-right: 10px" 
                    @change="handleSearch" />
                <el-input v-model="keywords" placeholder="请输入文章摘要或标题" style="width: 200px"
                    @keyup.enter="handleSearch" />
                <el-button type="primary" @click="handleSearch" style="margin-left: 10px">搜索</el-button>
                <el-button @click="handleReset" style="margin-left: 10px">重置</el-button>
            </div>
        </div>

        <!-- 发布列表 -->
        <div class="news-list">
            <div v-for="item in publishedList" :key="item.id" class="news-item">
                <!-- 新闻封面图 -->
                <img :src="item.coverImage || 'https://placehold.co/200x100?text=No+Image'" class="news-cover"
                    :alt="item.title" />

                <!-- 新闻信息 -->
                <div class="news-info">
                    <h4 class="news-title">{{ item.title }}</h4>
                    <div class="publish-info">
                        <span class="publish-tip">
                            <i class="el-icon-info" style="color: #f79020; margin-right: 5px"></i>
                            新闻发布时间：
                            <span :class="{ 'modified-time': item.modifiedNewsTime }">
                                {{ item.modifiedNewsTime || item.newsTime }}
                                <span v-if="item.modifiedNewsTime" class="modified-tag">已修改</span>
                            </span>
                        </span>
                        <a class="modify-link" href="javascript:;" @click="openModifyDialog(item)">修改时间</a>
                    </div>
                    <p class="news-abstract">{{ item.abstractReal }}</p>
                </div>

                <!-- 查看按钮 -->
                <el-button type="text" icon="el-icon-view" class="view-btn" />
            </div>

            <!-- 空状态 -->
            <el-empty v-if="publishedList.length === 0" description="暂无已发布新闻"></el-empty>
        </div>

        <!-- 分页 -->
        <div class="pagination">
            <span class="total-text">共{{ total }}条</span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
                :total="total" layout="prev, pager, next, ->, jumper, ->, sizes" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 修改时间弹窗 -->
        <el-dialog v-model="modifyDialogVisible" title="修改发布时间" width="400px" :close-on-click-modal="false">
            <el-form label-width="100px" class="modify-form">
                <el-form-item label="当前新闻" class="news-title-item">
                    <span class="news-title-text">{{ currentItem?.title }}</span>
                </el-form-item>
                <el-form-item label="发布时间" required>
                    <el-date-picker v-model="modifyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%" placeholder="选择新的发布时间" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="modifyDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmModify">确认修改</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>

.top-nav {
    background-color: #f5f7fa;
    padding: 15px 20px;
    border-bottom: 1px solid #eee;
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    color: #303133;
    margin: 0;
}

.published-news {
    padding: 20px;
    background-color: #fff;
    min-height: calc(100vh - 40px);
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.publish-count {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.filter-area {
    display: flex;
    align-items: center;
    gap: 10px;
}

.news-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.news-item {
    display: flex;
    align-items: flex-start;
    padding: 15px;
    border-radius: 6px;
    transition: all 0.2s;
    border: 1px solid #f0f0f0;
}

.news-item:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border-color: #e6f7ff;
}

.news-cover {
    width: 200px;
    height: 120px;
    border-radius: 4px;
    object-fit: cover;
    flex-shrink: 0;
}

.news-info {
    flex: 1;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.news-title {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
}

.publish-info {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    font-size: 14px;
}

.publish-tip {
    color: #606266;
}

.modified-time {
    color: #f56c6c;
    font-weight: 500;
}

.modified-tag {
    display: inline-block;
    margin-left: 5px;
    padding: 1px 6px;
    font-size: 12px;
    color: #fff;
    background-color: #f56c6c;
    border-radius: 10px;
}

.modify-link {
    color: #409eff;
    text-decoration: none;
    cursor: pointer;
}

.modify-link:hover {
    color: #66b1ff;
    text-decoration: underline;
}

.news-abstract {
    margin: 0;
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
}

.view-btn {
    color: #409eff;
    margin-left: 10px;
}

.pagination {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 30px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
}

.total-text {
    margin-right: 20px;
    color: #606266;
    font-size: 14px;
}

.modify-form {
    margin-top: 10px;
}

.news-title-item {
    padding-bottom: 5px;
    border-bottom: 1px dashed #f0f0f0;
}

.news-title-text {
    color: #606266;
    font-size: 14px;
    word-break: break-all;
}

@media (max-width: 768px) {
    .top-bar {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .filter-area {
        width: 100%;
        flex-wrap: wrap;
    }

    .news-item {
        flex-direction: column;
    }

    .news-cover {
        width: 100%;
        height: auto;
    }

    .news-info {
        margin-left: 0;
        margin-top: 15px;
    }
}
</style>